﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using takeabreak.Hook;

namespace takeabreak
{
    public partial class MainForm : Form
    {
        KeyboardHook k_hook;

        MouseHook m_hook;
        bool LeftTag = false;
        bool RightTag = false;
        Point p1 = new Point(0, 0);
        Point p2 = new Point(0, 0);
        static  int MAX = 60;
        int NOWMinutes = 0;
        C_MainForm c_MainForm = new C_MainForm(MAX);
        public MainForm()
        {
            InitializeComponent();
            timer1_Tick(null,null);
            SearchAutoRun(Application.ExecutablePath);
        }
        private void hook_KeyDown(object sender, KeyEventArgs e)
        {
            c_MainForm.SetStatus(true);
            ////判断按下的键（Alt + A）
            //if (e.KeyValue == (int)Keys.A && (int)Control.ModifierKeys == (int)Keys.Control)
            //{
            //    System.Windows.Forms.MessageBox.Show("按下了指定快捷键组合");
            //}
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.Visible = true;
        }

        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //System.Diagnostics.Process.Start("http://www.zhating.cn/index.php/post/62.html");
            c_MainForm.Clear();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.WindowState != FormWindowState.Minimized)
            {
                e.Cancel = true;
                //notifyIcon1.ShowBalloonTip(3000, "程序最小化提示", "图标已经缩小到托盘，打开窗口请双击图标或者右键【显示】即可。", ToolTipIcon.Info);
                this.Visible = false;
                this.ShowInTaskbar = false;
                notifyIcon1.Visible = true;
            }
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            k_hook.Stop();
            m_hook.UnHook();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            k_hook = new KeyboardHook();
            k_hook.KeyDownEvent += new KeyEventHandler(hook_KeyDown);//钩住键按下
            k_hook.Start();//安装键盘钩子

            m_hook = new MouseHook();
            m_hook.SetHook();
            m_hook.MouseDownEvent += mh_MouseDownEvent;
            m_hook.MouseUpEvent += mh_MouseUpEvent;
            m_hook.MouseMoveEvent += mh_MouseMoveEvent;

            this.Close();
        }
        //按下鼠标键触发的事件
        private void mh_MouseDownEvent(object sender, MouseEventArgs e)
        {
            c_MainForm.SetStatus(true);
        }
        //松开鼠标键触发的事件
        private void mh_MouseUpEvent(object sender, MouseEventArgs e)
        {
            c_MainForm.SetStatus(true);
        }

        private void mh_MouseMoveEvent(object sender, MouseEventArgs e)
        {
            c_MainForm.SetStatus(true);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (c_MainForm.GetStatus())
            {
                c_MainForm.Add();
            }
            else
            {
                c_MainForm.Minus();
            }
            NOWMinutes = c_MainForm.GetCount();
            if (NOWMinutes < MAX * 0.33)
            {
                this.notifyIcon1.Icon = System.Drawing.Icon.ExtractAssociatedIcon(@".\image\status\1.ico");
                this.notifyIcon1.Text = $"已累计{NOWMinutes}分钟,小于33%，请继续保持。";
            }
            else if (NOWMinutes >= MAX * 0.33 && NOWMinutes < MAX * 0.66)
            {
                this.notifyIcon1.Icon = System.Drawing.Icon.ExtractAssociatedIcon(@".\image\status\2.ico");
                this.notifyIcon1.Text = $"已累计{NOWMinutes}分钟,大于33%且小于66%，请进行适当放松。";
            }
            else
            {
                this.notifyIcon1.Icon = System.Drawing.Icon.ExtractAssociatedIcon(@".\image\status\3.ico");
                this.notifyIcon1.Text = $"已累计{NOWMinutes}分钟,大于66%，请尽快找时间休息，缓解眼部疲劳。";
            }
            if (NOWMinutes % 15 == 0)
            {
                notifyIcon1_MouseDoubleClick(null,null);
            }
        }

        private void tB_Minutes_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (int.Parse(this.tB_Minutes.Text)>0)
                {
                    MAX = int.Parse(this.tB_Minutes.Text);
                    c_MainForm.SetMax(MAX);
                    NotifyBalloon($"设置成功", $"请等待下次刷新后生效");
                }
                else
                {
                    NotifyBalloon($"设置异常",$"输入的数字不可为0\r\n设置未生效");
                }
            }
            catch (Exception ex)
            {
                NotifyBalloon($"设置异常", "输入的数字不正确或者为空" + ex);
                this.tB_Minutes.Text = "60";
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            NotifyBalloon($"最大值为{MAX}分钟", $"已累计工作{NOWMinutes}分钟");
        }
        public void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey reg = null;
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("该文件不存在!");
                String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                if (isAutoRun)
                    //reg.SetValue(name.Split('.')[0], fileName);
                    reg.SetValue(name, fileName, RegistryValueKind.String);
                else
                    reg.DeleteValue(name);
            }
            catch
            {
                //throw new Exception(ex.ToString());
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }
        public void SearchAutoRun(string fileName)
        {
            RegistryKey reg = null;
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("该文件不存在!");
                String name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                if (reg.GetValue(name) == null)
                {
                    checkBox1.Checked = false;
                }
                else
                {
                    checkBox1.Checked = true;
                }
            }
            catch
            {
                //throw new Exception(ex.ToString());
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                SetAutoRun(Application.ExecutablePath, true);  //设置自动启动当前程序
            }
            else
            {
                SetAutoRun(Application.ExecutablePath, false);  //取消自启动
            }
        }
        public void NotifyBalloon(string title, string text)
        {
            notifyIcon1.BalloonTipText = text;
            notifyIcon1.BalloonTipTitle = title;
            notifyIcon1.ShowBalloonTip(100);
        }
    }
}
